package com.xinxin.base.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author ys
 * @date 2020/5/16
 */
@Slf4j
public class RegionUtil {

    private static File file;

    private static void copyRegionDbFile() {
        String path = RegionUtil.class.getResource("/ip2region/ip2region.db").getPath();
        file = new File(path);
        if (file.exists()) {
            return;
        }

        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("ip2region/ip2region.db");
        path = System.getProperties().getProperty("java.io.tmpdir") + "/ip2region.db";
        file = new File(path);
        try {
            FileUtils.copyInputStreamToFile(in, file);
        } catch (IOException ignored) {
        }
    }

    public static String getCityInfo(String ip) {
        if (file == null || !file.exists()) {
            copyRegionDbFile();
        }

        DbSearcher searcher = null;
        try {
            if (!Util.isIpAddress(ip)) {
                log.error("Error: Invalid ip address");
            }

            searcher = new DbSearcher(new DbConfig(), file.getPath());
            return searcher.btreeSearch(ip).getRegion();
        } catch (Exception e) {
            log.error("获取地址信息异常，{}", e.getMessage());
            return null;
        } finally {
            if (searcher != null) {
                try {
                    searcher.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
}
